package com.cavy.platform.server.repository.impl;

import com.cavy.platform.server.domain.WorkSpace;
import com.cavy.platform.server.repository.WorkSpaceRepository;
import com.cavy.platform.server.util.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * author: 唐旭
 */
@Repository
public class WorkSpaceRepositoryImpl implements WorkSpaceRepository {
    @Value("${cavy.workspace.dir}")
    private String workSpaceDir;

    @Override
    public int countByName(String name) {
        File file = getSpaceDirFile(name);
        if (file.exists()) {
            return 1;
        }
        return 0;
    }

    private File getSpaceDirFile(String name) {
        return new File(workSpaceDir, name);
    }

    @Override
    public void create(WorkSpace name) {
        File spaceDirFile = getSpaceDirFile(name.getName());
        boolean mkdirs = spaceDirFile.mkdirs();
        if (!mkdirs) {
            throw new RuntimeException("创建工作空间路径:" + spaceDirFile.getPath() + "失败");
        }
    }

    @Override
    public void delete(String name) {
        File spaceDirFile = getSpaceDirFile(name);
        FileUtils.delFolder(spaceDirFile.getPath());
    }

    @Override
    public List<WorkSpace> getList() {
        File file = new File(workSpaceDir);
        File[] files = file.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.isDirectory();
            }
        });
        if (files == null || files.length == 0) {
            return Collections.emptyList();
        }
        List<WorkSpace> spaces = new ArrayList<>(files.length);
        for (File file1 : files) {
            spaces.add(new WorkSpace(file1.getName()));
        }
        return spaces;
    }
}
